package com.franklin.ideaplugin.easytesting.ui.execute;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.franklin.ideaplugin.api.ui.editor.CustomEditor;
import com.franklin.ideaplugin.api.ui.editor.FormatCustomJsonEditor;
import com.intellij.psi.PsiParameter;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Map;

/**
 * @author Ye Junhui
 * @since 2023/7/2 12:13
 */
public class JsonParameterFormProvider implements IParameterFormProvider {
    @Override
    public boolean isTarget(@NotNull Object defaultValue) {
        if (defaultValue instanceof Map){
            return true;
        }
        if (defaultValue instanceof Collection){
            return true;
        }
        if (defaultValue instanceof String){
            return JSON.isValidObject(((String) defaultValue));
        }
        return false;
    }

    @Override
    public ParameterTextComponent getForm(PsiParameter psiParameter, Object defaultValueOfPsiType, Object defaultValue) {
        CustomEditor customEditor = new CustomEditor(psiParameter.getProject(), CustomEditor.JSON_FILE_TYPE);
        if (defaultValue instanceof String){
            String strValue = (String) defaultValue;
            if (StrUtil.isNotBlank(strValue)) {
                customEditor.setText(strValue);
            }else {
                customEditor.setText(JSON.toJSONString(defaultValueOfPsiType,JSONWriter.Feature.PrettyFormat));
            }
        }else {
            String jsonString = JSON.toJSONString(defaultValue, JSONWriter.Feature.PrettyFormat);
            customEditor.setText(jsonString);
        }
        customEditor.setPsiType(psiParameter.getType());
        String title = psiParameter.getType().getPresentableText() + " " + psiParameter.getName();
        FormatCustomJsonEditor formatCustomEditor = new FormatCustomJsonEditor(title,customEditor);
        return new ParameterTextComponent(formatCustomEditor.getMainPanel()) {
            @Override
            public String getText() {
                return customEditor.getText();
            }

        };
    }
}
